package client;

import client.action.SayHelloAction;
import common.MessageID;
import online.chazi.netkit.NetkitClient;
import online.chazi.netkit.NetkitContext;
import online.chazi.netkit.Session;
import online.chazi.netkit.messaging.DefaultMessageEncrypt;
import online.chazi.netkit.messaging.Message;

import java.util.Random;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-04-24 17:31
 */
public class IMClient {

    private Session session;
    private NetkitClient client;
    private String host = "192.168.64.98"; //192.168.56.1  192.168.64.98
    private int port = 1688;

    private boolean loginFlag;

    public static void main(String[] args) throws Exception {
        new IMClient().start();
    }

    public void start() throws Exception {
        NetkitContext context = new NetkitContext(1);
        context.setMessageEncrypt(new DefaultMessageEncrypt());
        context.registerAction(MessageID.SAY_HELLO.id, SayHelloAction.class);
        client = new NetkitClient(context, host, port);
        restart();

        while (true) {

            try {
                Thread.sleep(3000L);

                if (loginFlag) {
                    System.out.println("send ..");
                    String message = "我是机器人B:" + new Random().nextInt(10000);
                    Message m = new Message(MessageID.SAY_HELLO.id, message);
                    getSession().sendMessage(m);
                } else restart();

            } catch (Exception e) {
                loginFlag = false;
                e.printStackTrace();
            }

        }
    }

    public void login() {
        System.out.println("login..");
        //todo your login logic
        loginFlag = true;
    }

    public void restart() throws Exception {
        System.out.println("restart...");
        session = client.createSession();
        login();
    }

    public Session getSession() {
        System.out.println("get session...");
        try {
            if (session == null || session.isClosed()) {
                if (!loginFlag) {
                    return null;
                }
                restart();
            }
            return session;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
